import DPlayer from 'dplayer'
// import flvjs from 'flv.js'
// import flvjs from '../../../../../../../../../../flv.js(1.6.2)/dist/flv'
// import flvjs from '../../../../assets/flv20170321.min'
import flvjs from '../../../../flv.js-master/dist/flv.js'

export default {
  methods: {
    // 初始化视频
    flvjsInitDPlayer(container, url) {
      this.canplay = false
      let flvPlayer
      if (!container || !url) return
      let type = 'customFlv';
      let volume = 0; //音量
      const that = this;
      const customType = {
        customFlv: function (video) {
          flvPlayer = flvjs.createPlayer(
            {
              type: 'flv',
              isLive: that.isLive,
              hasAudio: true,
              hasVideo: true,
              url
            },
            {
              enableWorker: false,//不启用分离线程
              lazyLoad: false,
              lazyLoadMaxDuration: 30 * 60,
              isLive: that.isLive,
              autoCleanupSourceBuffer:false,
              autoCleanupMaxBackwardDuration: 20 * 60,
              autoCleanupMinBackwardDuration: 15 * 60,
              seekType: 'range',
              enableStashBuffer: false, //关闭IO隐藏缓冲区,控制实时流
              stashInitialSize: 2046,
              isRecord: that.isRecord
            }
          )
          if (flvPlayer) { //直播流
            flvPlayer.attachMediaElement(video)
            flvPlayer.load()
          }
        },
      }
      let video = { //默认websocket
        url,
        type,
        customType,
      }
      if (this.isMP4) {
        type = 'auto'; //mp4
        video = {
          url,
          type,
        }
      }

      let player = new DPlayer({
        container,
        video,
        volume,
        live: this.isLive,
        autoplay: true,
        screenshot: true,
        mutex: false,
        hotkey: true,
      })
      if (flvPlayer) { //直播流
        player.flvPlayer = flvPlayer
      }

      player.video.playbackRate = this.times?.value || 1
      this.$nextTick(() => {
        this.isPlay = !player.video.paused
        this.updateDisplayScale()
      })
      player.on('play', () => {
        this.$emit('play', this.id)
        this.isPlay = true
        // const bolbList = this.player?.flvPlayer?.getBolbList();
        // console.log(Object.keys(bolbList).length, '初始化视频流数据', bolbList)
        // if (bolbList) {
        //   this.bolbListStart = bolbList;
        // }
      })
      player.on('destroy', () => {
        this.$emit('destroy', this.id)
        this.speed = 0
        this.isPlay = false
      })
      // player.on('timeupdate', (res) => {
      //   console.log('视频的缓存范围', player.video.buffered.end(0), '视频进度变化', player)
      // })
      if (flvPlayer) { //直播流
        this.flvPlayerEvent(flvPlayer)
      }
      // 监听video播放器播放时间的变化
      if (this.isLive) {
        player.on('timeupdate', function () {
          console.log("正在播放------live", player.video.buffered.end(0));
          console.log(player.video);
          // 计算表最新推流的时间和现在播放器播放推流的时间
          if (
            !player.video.currentTime ||
            !player.video.buffered.end(0) ||
            player.video.currentTime < 0 ||
            !player.video.buffered.end(0) < 0
          )
            return
          let differTime =
            player.video.buffered.end(0) - player.video.currentTime
          console.log(differTime);

          // 差值小于1.5s时根据1倍速进行播放
          if (differTime < 1) {
            player.video.playbackRate = 1
          }

          // 差值大于1.5s小于10s根据1.2倍速进行播放
          if (differTime < 10 && differTime > 1) {
            player.video.playbackRate = 2
            console.log(player.video.duration)
          }

          //console.log(videoFlvPlayer.buffered);
          // 差值大于10s时进行重新加载直播流
          if (differTime > 10) {
            console.log("重新刷新流!!");
            console.log(player.video.buffered.end(0),player.video.currentTime,differTime)

            if (player.video.buffered.end(0) > 10000) {
              player.play()
              return
            }
            player.video.playbackRate = 1
            player.video.currentTime = Math.floor(player.video.buffered.end(0))
            // 注意这里重新加载video是自己封装的方法，需要销毁video并重新创建video
            // $scope.videoPlay({liveUrl: videoFlvOptions.sources[0].src})
          }
          // this.$emit('timeupdate')
        })
      } else {
        player.on('timeupdate', (a, b, c) => {
          // console.log(player.video.buffered.end(0), player.video.currentTime);
          // let differTime =
          //   player.video.buffered.end(0) - player.video.currentTime;

          // if (differTime < 0)
          //   player.video.currentTime = Math.floor(player.video.buffered.end(0));
          this.axisNum = player.video.currentTime
          this.$emit('timeupdate', this.axisNum)
          if (player.video.buffered.length > 0)
            this.assistantNum = player.video.buffered.end(0)
          // this.assistantNum = player.video.buffered.end(0);
        })
      }
      player.on('durationchange', (a, b, c) => {
        this.duration = this.progOption.max || player.video.duration
      })
      this.flvjsEventText(player)
      return player
    },
    flvPlayerEvent(flvPlayer) {
      const self = this;
      let flvEventList = [
        { name: 'metadata_arrived', text: '用“ onMetaData”标记提供FLV文件（流）可以包含的元数据' },
        { name: 'scriptdata_arrived', text: '提供FLV文件（流）可以包含的脚本数据（OnCuePoint / OnTextData）' },
        { name: 'statistics_info', text: '提供播放统计信息，例如丢帧，当前速度等' },
        { name: 'media_info', text: '提供媒体的技术信息，例如视频/音频编解码器，比特率等' },
        // { name: 'NETWORK_ERROR', text: '与网络有关的错误' },
      ]
      flvEventList.forEach((item) => {
        // alert(123)
        flvPlayer.on(item.name, (res) => {
          if (item.name === 'STATISTICS_INFO' || item.name === 'statistics_info') {
            this.speed = res.speed.toFixed(1)
          } else {
            console.log(item.name, res);
          }
        })
      })

      flvjs.LoggingControl.addLogListener(function (type, str) {
        console.log(type, '进度监听类型', str, '进度监听')
        if (type === 'error') {
          if (str.indexOf('Loader error') !== -1 && self.errorImgSrc) {
            console.log('加载错误')
            setTimeout(() => {
              self.clearNotice()
              self.hideBaseImg();
              self.showErrorImg()
            }, 3000)
          }
        }
      });
    },
    // 事件测试
    flvjsEventText(player) {
      // 视频事件
      let videoEventList = [
        { name: 'abort', text: '当发生中止事件时运行脚本' },
        { name: 'canplay', text: '在有足够的数据可以播放时触发' },
        // {name: 'canplaythrough', text: '当媒介能够无需因缓冲而停止即可播放至结尾时运行脚本'},
        // {name: 'durationchange', text: '当媒介长度改变时运行脚本'},
        // {name: 'emptied', text: '当媒介资源元素突然为空时（网络错误、加载错误等）运行脚本'},
        { name: 'ended', text: '结束时触发' },
        { name: 'error', text: '发生错误时触发' },
        { name: 'loadeddata', text: '当加载媒介数据时运行脚本' },
        { name: 'loadedmetadata', text: '当媒介元素的持续时间以及其他媒介数据已加载时运行脚本' },
        { name: 'loadstart', text: '当浏览器开始加载媒介数据时运行脚本' },
        { name: 'mozaudioavailable', text: '' },
        { name: 'pause', text: '暂停时触发' }, // 暂停时触发
        // {name: 'play', text: '开始播放时触发'},
        // {name: 'playing', text: '播放时定期触发'},
        // {name: 'progress', text: '当浏览器正在取媒介数据时运行脚本'},
        // {name: 'ratechange', text: '当媒介数据的播放速率改变时运行脚本'},
        // {name: 'seeked', text: '当媒介元素的定位属性 [1] 不再为真且定位已结束时运行脚本'},
        // {name: 'seeking', text: '当媒介元素的定位属性为真且定位已开始时运行脚本'},
        {
          name: 'stalled',
          text: '当取回媒介数据过程中（延迟）存在错误时运行脚本',
        },
        {
          name: 'suspend',
          text: '当浏览器已在取媒介数据但在取回整个媒介文件之前停止时运行脚本',
        },
        // {name: 'timeupdate', text: '当媒介改变其播放位置时运行脚本'},
        // {name: 'volumechange', text: '当媒介改变音量亦或当音量被设置为静音时运行脚本'},
        // {name: 'waiting', text: '当媒介已停止播放但打算继续播放时运行脚本'}
        { name: 'waiting', text: '当媒介已停止播放但打算继续播放时运行脚本' },
      ]

      videoEventList.forEach((item) => {
        player.on(item.name, (a, b, c) => {
          // console.log('视频事件' + item.name + ':' + item.text)
          // console.log(a,b,c);
          if (item.name == 'error') {
            console.log('flvjs报错', a, b, c)
            if (this.$refs.video && this.realIsPlay) this.flvjsRelink()
          }
          if (item.name == 'ended') {
            console.log('flvjs结束')
            if (this.isLive && this.$refs.video && this.realIsPlay)
              this.flvjsRelink()
          }
          if (item.name == 'canplay') {
            this.canplay = true
          }
          if (item.name === 'loadeddata') {
            console.log('loadeddata', a, b, c) //dplayer-video

            // console.log(videoId.currentSrc, '媒体元素')
            this.clearNotice()
            this.hideBaseImg()
          }
          if (item.name === 'loadedmetadata') {
            console.log('loadedmetadata', a, b, c)
          }
          if (item.name == 'loadstart') {//浏览器开始加载媒介
            const mediaObj = document.querySelector("#video .dplayer-video");
            this.mediaObj = mediaObj; //挂载原生对象
            console.log('loadstart', a, b, c)
            const notice = {
              text: '连接成功，请稍候...',
              isLongDuration: true,
              style: {
                top: '65%',
                background: 'rgba(0,0,0,0)',
                color: '#fff'
              }
            }
            const imgWidth = this.$refs?.OceVideo?.offsetWidth || 0;
            const imgHeight = this.$refs?.OceVideo?.offsetHeight || 0;
            this.imgWidth = imgWidth;
            this.imgHeight = imgHeight;
            this.flvNotice(notice);
            // this.imageSrc = 'https://1301408934.vod2.myqcloud.com/d9f1f7c3vodcq1301408934/15bc22b75285890818252698642/469OlLni1HIA.jpg'
            if (this.imageSrc) {
              this.showImageSrc = true
              this.hideErrorImg()
            }
          }
        })
      })

    },
    // 重新连接
    flvjsRelink() {
      // console.log(connectTimeoutFlag);
      let connectTimeoutFlag
      if (connectTimeoutFlag) {
        clearTimeout(connectTimeoutFlag)
        connectTimeoutFlag = null
        return
      }
      this.destroy()
      connectTimeoutFlag = setTimeout(() => {
        console.log('回连-------------' + this.infoText)
        if (!this.isPlay && !this.player) {
          this.playVideo()
        } else {
          clearTimeout(connectTimeoutFlag)
          connectTimeoutFlag = null
        }
      }, 5000)
    },
    // 切换播放状态播放
    flvjsPlayVideo(isPlay) {
      // if (!this.player?.flvPlayer && this.player) { //录播流 - MP4
      //   this.player?.toggle() //切换播放
      //   return
      // }
      // if (typeof isPlay === 'boolean') {
      //   this.realIsPlay = isPlay
      //   if (!isPlay) {
      //     // this.destroy()
      //     this.pauseVideo()
      //   } else {
      //     this.player = this.initDPlayer(this.$refs.video, this.url)
      //   }
      //   return
      // }
      if (this.isPlay) {
        if (this.isMP4 || !this.isLive) {
          this.pauseVideo()
        } else {
          this.destroy()
        }
      } else {
        if (this.player && this.player.flvPlayer && (this.isMP4 || !this.isLive)) {
          this.replayVideo();
          return
        }
        this.player = this.initDPlayer(this.$refs.video, this.url)
      }
      if (this.player) { //已经播放初始化了
        this.isPlay = !this.isPlay;
        this.realIsPlay = isPlay
      }

    },
    flvjsPauseVideo() {
      this.player?.pause();
      this.player?.flvPlayer?.pause();
      this.playerPause();
      console.log('暂停播放', this.player.flvPlayer);
    },
    flvjsReplayVideo() {
      this.player?.play();
      this.player?.flvPlayer?.play();
      console.log('重新续播');
    },
    // 销毁
    flvjsDestroy() {
      if (!this.player?.flvPlayer && this.player) {
        this.isPlay = false
        if (!this.player || !this.player.destroy) return;
        this.player.destroy();
        this.assistantNum = 0;
        this.duration = 0;
        this.player = null
      } else if (this.player?.flvPlayer) {//直播流
        this.player.flvPlayer.unload() //去除视频加载
        this.player.flvPlayer.detachMediaElement() //将播放实例从节点中取出
        this.player.flvPlayer.destroy() //销毁播放实例
        this.player.flvPlayer = null
        this.player.destroy()
        this.assistantNum = 0
        this.duration = 0
        this.player = null
        // this.player.flvPlayer.pause()
      }
    },
    // 切换显示比例 speed 4:3 16:9 filling
    flvjsUpdateDisplayScale() {
      let scale = this.displayScale
      let videoEl = this.$refs.video.getElementsByClassName('dplayer-video')[0]
      let elWidth = this.$refs.video.clientWidth
      let elHeight = this.$refs.video.clientHeight
      let ratio = elWidth / elHeight
      if (videoEl) {
        switch (scale) {
          case '4:3':
            if (ratio > 4 / 3) {
              videoEl.style.height = '100%'
              videoEl.style.width = elHeight * (4 / 3) + 'px'
            } else {
              videoEl.style.height = elWidth * (3 / 4) + 'px'
              videoEl.style.width = '100%'
            }
            break
          case '16:9':
            if (ratio > 16 / 9) {
              videoEl.style.height = '100%'
              videoEl.style.width = elHeight * (16 / 9) + 'px'
            } else {
              videoEl.style.height = elWidth * (9 / 16) + 'px'
              videoEl.style.width = '100%'
            }
            break
          default:
            videoEl.style.height = ''
            videoEl.style.width = ''
        }
      }

    },
    //显示版本
    showVersion() {
      const version = flvjs.version;
      return version
      // document.title = document.title + " (v" + version + ")";
    }
  },
}
// </script>
